#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
待办清单自动化脚本 - 使用Edge浏览器
避免ChromeDriver下载问题
"""

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
import time
import pandas as pd


def auto_create_todos(url="http://localhost:5604", count=100):
    """自动化创建待办事项"""
    print("=" * 60)
    print("自动创建待办清单（使用Edge浏览器）")
    print("=" * 60)
    
    # 启动Edge浏览器
    print("启动Edge浏览器...")
    options = webdriver.EdgeOptions()
    options.add_argument('--disable-blink-features=AutomationControlled')
    
    driver = webdriver.Edge(options=options)
    driver.set_window_size(1920, 1080)
    
    todos_created = []
    
    try:
        # 打开页面
        print(f"访问页面: {url}")
        driver.get(url)
        time.sleep(3)
        
        # 查找添加待办的输入框
        print("\n查找添加待办的元素...")
        input_selectors = [
            (By.CSS_SELECTOR, ".head-input input"),
            (By.CSS_SELECTOR, "input[placeholder*='输入']"),
        ]
        
        input_element = None
        for by, selector in input_selectors:
            try:
                input_element = driver.find_element(by, selector)
                print(f"找到输入框: {selector}")
                break
            except:
                continue
        
        if not input_element:
            raise Exception("无法找到待办输入框")
        
        # 查找搜索/添加按钮
        button = None
        try:
            button = driver.find_element(By.CSS_SELECTOR, ".head-input button")
            print("找到添加按钮")
        except:
            print("使用回车键添加")
        
        print("\n开始创建待办事项...")
        print("-" * 60)
        
        # 创建指定数量的待办
        for i in range(1, count + 1):
            try:
                todo_content = f"待办事项 {i}: 这是第{i}个任务"
                
                input_element.clear()
                input_element.send_keys(todo_content)
                time.sleep(0.3)
                
                if button:
                    button.click()
                else:
                    input_element.send_keys("\n")
                
                todos_created.append({
                    "序号": i,
                    "待办内容": todo_content,
                    "创建时间": time.strftime("%Y-%m-%d %H:%M:%S"),
                })
                
                if i % 10 == 0:
                    print(f"已创建 {i}/{count} 个待办...")
                
                time.sleep(0.2)
                
            except Exception as e:
                print(f"创建第{i}个待办失败: {e}")
                continue
        
        print("-" * 60)
        print(f"成功创建 {len(todos_created)} 个待办事项")
        
        time.sleep(2)
        all_todos = driver.find_elements(By.CSS_SELECTOR, ".item .content")
        print(f"\n页面现有待办总数: {len(all_todos)}")
        
        # 导出Excel
        if todos_created:
            filename = f"待办清单_{time.strftime('%Y%m%d_%H%M%S')}.xlsx"
            df = pd.DataFrame(todos_created)
            df.to_excel(filename, index=False)
            print(f"\n结果已导出: {filename}")
        
    except Exception as e:
        print(f"执行出错: {e}")
        import traceback
        traceback.print_exc()
    finally:
        print("\n等待5秒后关闭浏览器...")
        time.sleep(5)
        driver.quit()
        print("浏览器已关闭")


if __name__ == "__main__":
    import sys
    
    url = "http://localhost:5604"
    count = 100
    
    if len(sys.argv) > 1:
        url = sys.argv[1]
    if len(sys.argv) > 2:
        count = int(sys.argv[2])
    
    print("\n待办清单自动创建脚本")
    print("使用: Edge浏览器")
    print("-" * 60)
    print(f"URL: {url}")
    print(f"数量: {count}")
    print("-" * 60)
    
    auto_create_todos(url, count)

